/*============================================================================
 * Copyright 2009 VMware Inc.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at: http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 ============================================================================*/

package com.vmware.vcloud;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.vmware.vcloud.rest.RestClient;
import com.vmware.vcloud.rest.StreamUtil;

/**
 * @author Steve Jin (sjin@vmware.com)
 */

public class VCloudInstance 
{
	RestClient rc = null;
	String version = null;
	Org[] orgs = null;
	
	public VCloudInstance(String baseUrl, String username, String password) throws MalformedURLException, IOException
	{
		rc = new RestClient(baseUrl, username, password);
		
		String getStr = rc.get("versions");
		
		System.out.println(getStr);

		try
		{
		    Document doc = DocumentHelper.parseText(getStr);
			Element root = doc.getRootElement();
			
			Element verInfo = root.element("VersionInfo");
			version = verInfo.elementText("Version");
			String loginUrl = verInfo.elementText("LoginUrl");
			
	        String userPassword = username + ":" + password; 
	        String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
	
	        HttpURLConnection uc = (HttpURLConnection) new URL(loginUrl).openConnection();
	        uc.setRequestMethod("POST");
	        uc.setRequestProperty  ("Authorization", "Basic " + encoding);
	        uc.setRequestProperty("Content-Length", "0");
	        InputStream is = (InputStream)uc.getInputStream();
	        String cookie = uc.getHeaderField("Set-Cookie");
	        rc.setCookie(cookie);
	        
	        StringBuffer sb = StreamUtil.readStream(is);
	        orgs = parseOrgs(sb.toString());
		} catch(DocumentException de)
		{
			throw new RuntimeException(de);
		}
	}
	
	private Org[] parseOrgs(String xmlText) throws DocumentException, MalformedURLException
	{
		Document doc = DocumentHelper.parseText(xmlText);
		Element root = doc.getRootElement();
		
		List<?> elms = root.elements("Org");
		Org[] os = new Org[elms.size()];
		
		for(int i=0; i<elms.size(); i++)
		{
			Element node = (Element) elms.get(i);
			String href = node.attributeValue("href");
			String name = node.attributeValue("name");
			os[i] = new Org(rc, href, name);
		}
		return os;
	}
	
	public String getVersion()
	{
		return version;
	}
	
	public Org[] getOrgs()
	{
      return orgs;
	}
	
	public RestClient getRC()
	{
		return rc;
	}
}